<?php
/**
  * //w/w/w.s/h/u/o/t//u/p/u c/o/m  说 图/谱/源/码/分/享
 */
defined("IN_IA")or exit("Access denied");
global $_GPC,$_W;
$uniacid=$_GPC['uniacid'];
$op=$_GPC['op'] ? $_GPC['op'] :"index";
$uid=$_GPC['uid'];

//初始化获取签到页面的信息
if($op=='getSignData'){
	$request=array();
	//获取签到数据
	$year=intval($_GPC['year']);
	$month=intval($_GPC['month']);
	$signData=pdo_getall('cqkundian_farm_sign',array('year'=>$year,'month'=>$month,'uid'=>$uid,'uniacid'=>$uniacid));
	$request['signData']=$signData;

	//判断今日是否签到
	$today=date("d",time());
	$todaySign=pdo_get('cqkundian_farm_sign',array('year'=>$year,'month'=>$month,'uid'=>$uid,'uniacid'=>$uniacid,'day'=>$today));
	if($todaySign){
		$request['is_sign']=1;	//已签到
	}else{	
		$request['is_sign']=2; //未签到
        //判断昨天是否签到
        $yesterday_year=date("Y",strtotime("-1 day"));
        $yesterday_month=date("m",strtotime("-1 day"));
        $yesterday_day=date("d",strtotime("-1 day"));
        $signData=pdo_get('cqkundian_farm_sign',array('year'=>$yesterday_year,'month'=>$yesterday_month,'day'=>$yesterday_day,'uid'=>$uid,'uniacid'=>$uniacid));
        if(empty($signData)){
            pdo_update('cqkundian_farm_user',array('continue_day'=>0),array('uid'=>$uid));
        }
	}

    $userData=pdo_get('cqkundian_farm_user',array('uid'=>$uid,'uniacid'=>$uniacid));
    $request['userData']=$userData;

	//关于我们
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    if($aboutData['sign_banner']==''){
        $aboutData['sign_banner']=$_W['siteroot'].'addons/kundian_farm/resource/image/icon-03.png';
    }
    $request['aboutData']=$aboutData;
	echo json_encode($request);die;
}

//签到
if($op=='addSign'){
	$request=array();
    if(empty($_GPC['year'])){
        $year=date("Y",time());
    }else{
        $year=intval($_GPC['year']);
    }
	if(empty($_GPC['month'])){
        $month=date("m",time());
    }else{
        $month=intval($_GPC['month']);
    }
    if(empty($_GPC['day'])){
        $day=date('d',time());
    }else{
        $day=intval($_GPC['day']);
    }
	$signData=pdo_get('cqkundian_farm_sign',array('year'=>$year,'month'=>$month,'day'=>$day,'uid'=>$uid,'uniacid'=>$uniacid));
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));

	if(empty($signData)){
		$insertSign=array(
			'uid'=>$uid,
			'sign_time'=>time(),
			'year'=>$year,
			'month'=>$month,
			'day'=>$day,
			'uniacid'=>$uniacid,
			'score'=>$aboutData['sign_integral'],		//签到一次获取 X 积分
		);
		$res=pdo_insert('cqkundian_farm_sign',$insertSign);	
		if($res){
            $setData=pdo_get('cqkundian_farm_set',array('uniacid'=>$uniacid,'ikey'=>'is_open_sign_card_score'));
            if($setData && $setData['value']==1) {
                //签到获取积分卡积分
                cardSign($uid, $uniacid);
            }
			//判断昨天是否签到
			$before_day=strtotime(date("Y-m-d",strtotime("-1 day")));
			$today_day=strtotime(date("Y-m-d"));
			$before_where['sign_time <']=$today_day;
			$before_where['sign_time >']=$before_day;
			$before_sign=pdo_get('cqkundian_farm_sign',$before_where);
			if($before_sign){
				$update_user=pdo_update('cqkundian_farm_user',array('score +='=>$aboutData['sign_integral'],'continue_day +='=>1),array('uid'=>$uid,'uniacid'=>$uniacid));
			}else{
				$update_user=pdo_update('cqkundian_farm_user',array('score +='=>$aboutData['sign_integral'],'continue_day'=>1),array('uid'=>$uid,'uniacid'=>$uniacid));
			}
			if($aboutData['sign_integral']) {
                insertIntegral($uniacid, $uid, $aboutData['sign_integral'], '签到');
            }
			if($update_user){
				$request['code']=1;
				$request['day']=$day;
			}else{
				$request['code']=4;		//更新数据失败
			}
		}else{
			$request['code']=2;		//签到失败
		}

		$userData=pdo_get('cqkundian_farm_user',array('uid'=>$uid,'uniacid'=>$uniacid));
		$request['userData']=$userData;
	}else{
		$request['code']=3;		//今日已签到
	}
	echo json_encode($request);die;
}

//切换月份
if($op=='getChangeSign'){
	$request=array();
	$year=$_GPC['year'];
	$month=$_GPC['month'];
	$signData=pdo_getall('cqkundian_farm_sign',array('year'=>$year,'month'=>$month,'uid'=>$uid,'uniacid'=>$uniacid));
	$request['signData']=$signData;
	echo json_encode($request);die;
}

//获取积分记录
if($op=='getRecord'){
    $request=array();
    if(empty($_GPC['page'])){
        $page=$_GPC['page'];
    }else{
        $page=intval($_GPC['page']);
    }
    $recordData=pdo_getall('cqkundian_farm_integral_record',array('uniacid'=>$uniacid,'uid'=>$uid),'','','id desc',array($page,15));
    for($i=0;$i<count($recordData);$i++){
        $recordData[$i]['create_time']=date('Y-m-d',$recordData[$i]['create_time']);
    }
    $request['recordData']=$recordData;
    echo json_encode($request);die;
}

if($op=='getSignRule'){
    $aboutData=pdo_get('cqkundian_farm_about',array('uniacid'=>$uniacid));
    echo json_encode(array('aboutData'=>$aboutData));die;
}


//绑定积分兑换卡
if($op=='addCard'){
    $request=array();
    $card_num=$_GPC['card_num'];
    $card_pwd=$_GPC['card_pwd'];
    $uid=$_GPC['uid'];
    $cardData=pdo_get('cqkundian_farm_card',array('uniacid'=>$uniacid,'card_num'=>$card_num,'card_pwd'=>$card_pwd));
    if(!empty($cardData)) {
        if ($cardData['status'] == 0) {  //未激活
            $setData=pdo_get('cqkundian_farm_set',array('uniacid'=>$uniacid,'ikey'=>'card_expire_time'));
            $expire_time=$setData['value']*86400+time();
            $res=pdo_update('cqkundian_farm_card',array('uid'=>$uid,'status'=>1,'use_time'=>time(),'expire_time'=>$expire_time),array('uniacid'=>$uniacid,'card_num'=>$card_num,'card_pwd'=>$card_pwd));
            if($res){
                $request['code']=0; //绑定成功
            }else{
                $request['code']=1;  //绑定失败
            }

        }else{
            $request['code']=3;//卡号已被绑定
        }
    }else{
        $request['code']=2;  //卡号或密码输入错误
    }
    echo json_encode($request);die;
}

//获取激活兑换卡记录
if($op=='getCardRecord'){
    $request=array();
    $cardData=pdo_getall('cqkundian_farm_card',array('uniacid'=>$uniacid,'uid'=>$uid));
    for ($i=0;$i<count($cardData);$i++){
        $cardData[$i]['use_time']=date("Y年m月d日",$cardData[$i]['use_time']);
        $cardData[$i]['expire_time']=date("Y年m月d日",$cardData[$i]['expire_time']);
    }
    $request['cardData']=$cardData;
    echo json_encode($request);die;
}


//测试
if($op=='signCard'){
    var_dump(diffBetweenTwoDays(date("Y-m-d", time()), '2018-07-17'));
}


/**
 * 签到获取积分卡积分
 * @param $uid
 * @param $uniacid
 */
function cardSign($uid,$uniacid){
//    $setData=pdo_get('cqkundian_farm_set',array('uniacid'=>$uniacid,'ikey'=>'card_score'));
    //查询我的积分卡
    $cardData=pdo_getall('cqkundian_farm_card',array('uniacid'=>$uniacid,'uid'=>$uid,'status'=>1));
    $oldSetData=pdo_getall('cqkundian_farm_set',array('uniacid'=>$uniacid,'ikey'=>array('card_tag_title','card_score')));
    $setData=array();
    foreach ($oldSetData as $key=>$value){
        $setData[$value['ikey']]=$value['value'];
    }
    if($setData['card_tag_title']){
        $card_tag_title=$setData['card_tag_title'];
    }else{
        $card_tag_title='兑换卡获取积分';
    }
    if(!empty($cardData)) {
        $today_score = 0;
        for ($i = 0; $i < count($cardData); $i++) {
            //判断该积分卡是否过期
            if ($cardData[$i]['expire_time'] < time()) {
                pdo_update('cqkundian_farm_card', array('status' => 2), array('uniacid' => $uniacid, 'uid' => $uid, 'card_num' => $cardData[$i]['card_num']));
            } else {
                //查询我的积分卡签到记录
                $cardRecord = pdo_getall('cqkundian_farm_card_record', array('uniacid' => $uniacid, 'uid' => $uid, 'card_num' => $cardData[$i]['card_num']), '', '', 'id desc');
                if (empty($cardRecord)) {  //没有签到记录就判断领取时间与当前时间相差天数
                    $between_day = diffBetweenTwoDays(date("Y-m-d", time()), date("Y-m-d", $cardData[$i]['use_time']));
                    if ($between_day == 0) {
                        $record = array(
                            'card_num' => $cardData[$i]['card_num'],
                            'uid' => $uid,
                            'create_time' => time(),
                            'year' => date("Y"),
                            'month' => date("m"),
                            'day' => date("d"),
                            'uniacid' => $uniacid,
                            'score' => $setData['card_score'],
                        );
                        $today_score += $setData['card_score'];
                        pdo_insert('cqkundian_farm_card_record', $record);
                    } else {
                        for ($d = $between_day ; $d >= 0; $d--) {
                            $record = array(
                                'card_num' => $cardData[$i]['card_num'],
                                'uid' => $uid,
                                'create_time' => time(),
                                'year' => date("Y", strtotime("-$d day")),
                                'month' => date("m", strtotime("-$d day")),
                                'day' => date("d", strtotime("-$d day")),
                                'uniacid' => $uniacid,
                                'score' => $setData['card_score'],
                            );
                            $today_score += $setData['card_score'];
                            pdo_insert('cqkundian_farm_card_record', $record);
                        }
                    }
                } else {
                    $between_day = diffBetweenTwoDays(date("Y-m-d"), $cardRecord[0]['year'] . '-' . $cardRecord[0]['month'] . '-' . $cardRecord[0]['day']);
                    if ($between_day == 0) {
                        $record = array(
                            'card_num' => $cardData[$i]['card_num'],
                            'uid' => $uid,
                            'create_time' => time(),
                            'year' => date("Y"),
                            'month' => date("m"),
                            'day' => date("d"),
                            'uniacid' => $uniacid,
                            'score' => $setData['card_score'],
                        );
                        $today_score += $setData['card_score'];
                        pdo_insert('cqkundian_farm_card_record', $record);
                    } else {
                        for ($d = $between_day-1 ; $d >= 0; $d--) {
                            $record = array(
                                'card_num' => $cardData[$i]['card_num'],
                                'uid' => $uid,
                                'create_time' => time(),
                                'year' => date("Y", strtotime("-$d day")),
                                'month' => date("m", strtotime("-$d day")),
                                'day' => date("d", strtotime("-$d day")),
                                'uniacid' => $uniacid,
                                'score' => $setData['card_score'],
                            );
                            $today_score += $setData['card_score'];
                            pdo_insert('cqkundian_farm_card_record', $record);
                        }
                    }

                }

            }
        }
        //插入签到记录
        pdo_update('cqkundian_farm_user', array('score +=' => $today_score), array('uniacid' => $uniacid, 'uid' => $uid));
        insertIntegral($uniacid, $uid, $today_score, $card_tag_title);
    }
}


/**
 * 添加积分记录
 * @param $uniacid
 * @param $uid
 * @param $score
 */
function insertIntegral($uniacid,$uid,$score,$body){
    $userData=pdo_get('cqkundian_farm_user',array('uid'=>$uid,'uniacid'=>$uniacid));
    $insertData=array(
        'uid'=>$uid,
        'uniacid'=>$uniacid,
        'create_time'=>time(),
        'score_type'=>1,
        'score'=>$score,
        'body'=>$body,
        'now_score'=>$userData['score'],
    );
    pdo_insert('cqkundian_farm_integral_record',$insertData);
}

/**
 * 计算两个时间段之间相隔的天数
 * @param $day1 2018-05-26
 * @param $day2 2018-07-06
 * @return float|int
 */
function diffBetweenTwoDays ($day1, $day2){
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);
    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}
